//
//  RemindViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/2.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "RemindViewController.h"
#import "RemindTableViewCell.h"
#import "RemindView.h"
#import "AddRemindViewController.h"
#import "DTVoiceManager.h"
#import "ZZiflyTool.h"
#import "RemindModel.h"
#import "GetRemindListApi.h"
#import "DeleteRemindApi.h"
#import "SaveRemindApi.h"

@interface RemindViewController ()<UITableViewDelegate,UITableViewDataSource,MGSwipeTableCellDelegate>

@property(nonatomic,strong) RemindView *containerView;


@property(nonatomic,strong) NSMutableArray *dataSource;

@end

@implementation RemindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self getRemindList];
    
//    RemindModel *remindModel = [[RemindModel alloc] init];
//    remindModel = [remindModel handelRemindResult:@"提醒某某喝茶2017年7月5日8:3"];
//    NSLog(@"%@----%@----%@",remindModel.title,remindModel.date,remindModel.time);
}


#pragma mark --- 点击事件
- (void)onRightButtonClick:(id)sender
{
    AddRemindViewController *vc = [AddRemindViewController new];
    RemindModel *model = [[RemindModel alloc] init];
    model.ids = @"0";
    vc.remindModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)holdOnVoiceButton
{
//    [[ZZiflyTool shareTool] startRecognizer:^(IFlySpeechError *error, NSString *result) {
//
//
//        if (error) {
//
////            [self showMes:error.errorDesc];
//
//            return;
//        }
//        NSLog(@"语音结果：%@",result);
//
////        [self showMes:str];
//
//    }];
//    [[DTVoiceManager shareManager] voiceListen:^(NSString *voiceString) {
//        NSLog(@"result:%@",voiceString);
//    }];
}

- (void)touchUpVoiceButton
{
//    [[DTVoiceManager shareManager] voiceStop];
//    [[ZZiflyTool shareTool] cancelRecognizer];
    __weak typeof(self) weakSelf = self;
    [[ZZiflyTool shareTool] startRecognizer:^(IFlySpeechError *error, NSString *result) {
        if (error)
        {
            //            [self showMes:error.errorDesc];
            return;
        }
        NSArray *str1=[result componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@",，！？。"]];
        NSString *resul=[str1 componentsJoinedByString:@""];
        NSLog(@"语音结果：%@",resul);
//        [weakSelf handleResult:resul];
        RemindModel *remindModel = [[RemindModel alloc] init];
        remindModel = [remindModel handelRemindResult:resul];
        NSLog(@"%@----%@----%@",remindModel.content,remindModel.date,remindModel.time);
        if (remindModel.content && remindModel.date && remindModel.time)
        {
            [self saveRemindWithModel:remindModel];
        }

        //        [self showMes:str];
        
    }];
}

#pragma mark -- 事件处理
- (void)getRemindList
{
    GetRemindListApi *api = [[GetRemindListApi alloc] initWithDic:@{@"sn":EXRACT_OBJECT(DEVICEMAC)}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:[NSArray yy_modelArrayWithClass:[RemindModel class] json:request.responseJSONObject[@"data"]]];
        [self.containerView.tableView reloadData];
    } failure:nil];
}

- (void)saveRemindWithModel:(RemindModel *)model
{
    [[ZZiflyTool shareTool] cancelRecognizer];
    NSString *string = [model.content stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *remindTime = [model getDateString];
    SaveRemindApi *api = [[SaveRemindApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"remind_time":remindTime,@"content":string,@"id":@"0"}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showSuccessWithStatus:[request responseJSONObject][@"errmsg"]];
        [self getRemindList];
    } failure:nil];
}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(180);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RemindTableViewCell *cell = [RemindTableViewCell cellWithTableView:tableView forIndexPath:indexPath];
    RemindModel *model = self.dataSource[indexPath.section];
    cell.iconImageView.image = imageWithName(@"icon_time");
    cell.timeLabel.text = model.time;
    cell.dateLabel.text = model.date;
    cell.titleLabel.text = model.content;
    cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"删除" backgroundColor:rgba(251,74,79,1)],[MGSwipeButton buttonWithTitle:@"编辑" backgroundColor:rgba(255,151,38,1)]];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(BOOL) swipeTableCell:(UITableViewCell *) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    NSIndexPath *indexPath = [self.containerView.tableView indexPathForCell:cell];
    
    if (direction == MGSwipeDirectionRightToLeft)
    {
        RemindModel *model = self.dataSource[indexPath.section];
        switch (index) {
            case 0:
            {
                [[AlertViewManager shareManager] initWithTitle:@"提示" message:@"您确定要删除此提醒？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                    if (buttonIndex == 1)
                    {
                        DeleteRemindApi *api = [[DeleteRemindApi alloc] initWithDic:@{@"id":model.ids,@"sn":EXRACT_OBJECT(DEVICEMAC)}];
                        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                            [SVProgressHUD showSuccessWithStatus:[request responseJSONObject][@"errmsg"]];
                            [self getRemindList];
                        } failure:nil];
                    }
                }];
            }
                break;
                
            case 1:
            {
                AddRemindViewController *vc = [[AddRemindViewController alloc] init];
                vc.remindModel = model;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
        
    }
    
    return YES;
}

#pragma mark --- 懒加载
- (RemindView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[RemindView alloc]init];
        [superView addSubview:_containerView];
        _containerView.tableView.delegate = self;
        _containerView.tableView.dataSource = self;
        [_containerView.voiceButton addTarget:self action:@selector(holdOnVoiceButton) forControlEvents:UIControlEventTouchDown];
        [_containerView.voiceButton addTarget:self action:@selector(touchUpVoiceButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}





- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [NSMutableArray arrayWithCapacity:3];
    }
    return _dataSource;
}


#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    [self.view bringSubviewToFront:self.navigationBar];
}

- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"提醒"];
    [self setRightButtonImage:imageWithName(@"nav_add")];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
